package 链表;

import com.sun.org.apache.bcel.internal.generic.NEW;

/**
 * https://leetcode-cn.com/problems/merge-two-sorted-lists/
 *
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 */
public class _21_合并两个有序链表 {
     public class ListNode {
       int val;
       ListNode next;
       ListNode() {}
       ListNode(int val) { this.val = val; }
       ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null && list2 == null) return null;
        if(list1 ==  null) return list2;
        if(list2 == null) return list1;

        ListNode newList = new ListNode(0);
        ListNode tmp = newList;

        while(list1!=null && list2!=null){
            if(list1.val<= list2.val){
                tmp.next = list1;
                list1 = list1.next;
            }else{
                tmp.next = list2;
                list2 = list2.next;
            }
            tmp = tmp.next;
        }
        if(list1 == null){
            tmp.next = list2;
        }else{
            tmp.next = list1;
        }
        return newList.next;

    }

    public ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
        if(list1 == null && list2 == null) return null;
        if(list1 == null) return list2;
        if(list2 == null) return list1;

        ListNode newList = new ListNode(0);
        ListNode p = newList;

        //循环遍历两个链表的节点进行比较
        while(list1!=null && list2!=null){
            if(list1.val< list2.val){
                p.next = list1;
                list1 = list1.next;
            }else{
                p.next = list2;
                list2 = list2.next;
            }
            p = p.next;
        }

        if(list1!=null){
            p.next = list1;
        }

        if(list2!=null){
            p.next = list2;
        }
        return newList.next;
    }

}
